﻿'
' Boogaloo® - http://www.mindfly.com
' Copyright (c) 2008
' by Mindfly, Inc.
'
' Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated 
' documentation files (the "Software"), to deal in the Software without restriction, including without limitation 
' the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and 
' to permit persons to whom the Software is furnished to do so, subject to the following conditions:
'
' The above copyright notice and this permission notice shall be included in all copies or substantial portions 
' of the Software.
'
' THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
' INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
' DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
' SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
' SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
' WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
' THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

Imports System.IO
Imports Boogaloo.Core
Imports Boogaloo.Core.BLL
Imports Boogaloo.Core.UI
Imports Boogaloo.Admin.UI.Controls

Namespace UI.Webpages


    Partial Public Class UserControlEditor
        Inherits BaseAdminPage

        Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

            hyp_cancel.NavigateUrl = Request.Url.PathAndQuery

            If Not Page.IsPostBack Then
                lbl_fileexists.Visible = False


                BindPage()

            End If

        End Sub

        Private Sub BindPage()

            Dim ascxfiles As String() = Groove.GetDirectoryFiles(ascx_directory, "*.ascx")
            Dim ascx As String = String.Empty
            ddl_ascx.Items.Clear()
            For Each ascx In ascxfiles               
                ddl_ascx.Items.Add(New ListItem(Path.GetFileName(ascx), Groove.RewriteServerPathAsVirtualPath(ascx, False)))
            Next


            ddl_ascx.Items.Insert(0, New ListItem("Create a new user control", "0"))

            If Not String.IsNullOrEmpty(file_path) Then ddl_ascx.SelectedValue = RemoveVirtualDirectoryFromFilePath(Groove.RewriteServerPathAsVirtualPath(file_path, False))

            If ddl_ascx.SelectedValue = "0" Then

                ' show the new file stuff
                ulCodeTemplates.Visible = True
                
                dwiz.Visible = False
                designer_info.Visible = False

            Else

                Dim allowDelete As New ArrayList
                If ddl_ascx.Items.Count > 0 Then
                    Dim rc As RegisteredControl = Nothing
                    For Each rc In Groove.admin_root.registered_controls
                        allowDelete.Add(Server.MapPath(rc.ascx_source))
                        If Not String.IsNullOrEmpty(rc.ascx_source_editor) Then allowDelete.Add(Server.MapPath(rc.ascx_source_editor))
                    Next
                End If

                ' hide the new file stuff
                ulCodeTemplates.Visible = False
                If lbl_txt_ascx_name.Visible Then lbl_txt_ascx_name.Visible = False

                ' set the file contents
                txt_ascx.Text = Groove.GetTextFileContents(file_path)

                ' turn on the delete wizard
                dwiz.Visible = Not allowDelete.Contains(ddl_ascx.SelectedValue)

                designer_info.Visible = True
                Dim tagname As String = ddl_ascx.SelectedValue.Substring(ddl_ascx.SelectedValue.LastIndexOf("/") + 1).ToLower.Replace(".ascx", "").ToLower

                Dim register As String = Server.HtmlEncode(String.Format("<%@ register tagprefix=""mfb"" tagname=""{0}"" src=""{1}"" %>", tagname, ddl_ascx.SelectedValue))
                lbl_register.Text = register

                Dim callout As String = Server.HtmlEncode(String.Format("<mfb:{0} runat=""server"" />", tagname))
                lbl_callout.Text = callout

            End If

        End Sub

        Protected Sub lb_save_Click(ByVal sender As Object, ByVal e As EventArgs) Handles lb_save.Click

            If Page.IsValid Then

                If lbl_txt_ascx_name.Visible Then
                    file_path = Node.UrlRewriteVirtualPathEncoder(txt_ascx_name.Text).Replace("-", String.Empty)

                    file_path = String.Format("{0}{1}.ascx", ascx_directory, file_path)
                    If File.Exists(file_path) Then
                        lbl_fileexists.Visible = True
                        file_path = String.Empty
                        Exit Sub
                    End If
                Else
                    file_path = Server.MapPath("~" & ddl_ascx.SelectedValue)
                End If

                Groove.WriteTextFileContents(file_path, txt_ascx.Text)

                BindPage()

            End If

        End Sub

        Private Sub dwiz_Click(ByVal sender As Object, ByVal e As EventArgs) Handles dwiz.Click

            file_path = Server.MapPath("~" & ddl_ascx.SelectedValue)

            File.Delete(file_path)

            Groove.RefreshPage()

        End Sub

        Private Sub ddl_ascx_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs) Handles ddl_ascx.SelectedIndexChanged

            If ddl_ascx.SelectedValue = "0" Then
                Groove.RefreshPage()
            Else
                file_path = Server.MapPath("~" & ddl_ascx.SelectedValue)
                BindPage()
            End If
            
        End Sub

        Private Function RemoveVirtualDirectoryFromFilePath(ByVal fpath As String) As String
            If Not String.Equals(Request.ApplicationPath, "/") Then
                If fpath.StartsWith(Request.ApplicationPath) Then fpath = fpath.Remove(0, Request.ApplicationPath.Length)
            End If

            Return fpath
        End Function


        Private _ascx_directory As String = Server.MapPath(CoreSettings.GetSetting("ADMIN_UserControlEditorPath"))
        Protected ReadOnly Property ascx_directory() As String
            Get
                Return _ascx_directory
            End Get
        End Property



        Protected ReadOnly Property code_template_directory() As String
            Get
                Return Server.MapPath(Groove.path_code_templates)
            End Get
        End Property



        Private _file_path As String = String.Empty
        Public Property file_path() As String
            Get
                Return _file_path
            End Get
            Set(ByVal value As String)
                _file_path = value
            End Set
        End Property


    End Class

End Namespace